# -*- coding:utf-8 -*-
"""
Created on 2 jul 2011

@author: Olof Manbo
"""
import os
import logging
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from math import sqrt
import test_pb2
import sveanasRequests

import random
import httplib

class Main(webapp.RequestHandler):
    def get(self):
        
        courtMap = [        
        -1073739776,
        -1073739264,
        -1073739008,
        -1073738880,
        -1073738816,
        -1073738784,
        ]
        
        
        

        #processResponse = sveanasRequests.sendProcessRequest(test_pb2.ProcessRequest.RUN, "Run")
        #logging.info(processResponse.success)
        nodeResponse = sveanasRequests.sendNodeRequest()
        logging.info(nodeResponse)
        logging.info(nodeResponse.node)
        for node in nodeResponse.node:
            logging.info("%s %i %i"%(node.resource_key, node.x, node.y))            

        xlist = [None for dummy in range(6)]
        ylist = [None for dummy in range(6)]
        noOfFarms = [0 for dummy in range(6)]
        for node in nodeResponse.node:
            if courtMap.count(node.resource_key) == 1:
                xlist[courtMap.index(node.resource_key)] = node.x
                ylist[courtMap.index(node.resource_key)] = node.y
        r = 100
        SCALE = 20.0
        plote = ""
        numberOfTwos = 0
        numberOfOthers = 0
        for node in nodeResponse.node:
            logging.info(node)
            grop = 0
            if node.resource_key == 2400:
                plote += 'ctx.strokeStyle = "rgb(0,0,0)";\n'
                for n in range(6):
                    if sqrt((xlist[n]-node.x)**2+(ylist[n]-node.y)**2) < r:
                        noOfFarms[n] += 1
            elif courtMap.count(node.resource_key) == 1:
                plote += 'ctx.strokeStyle = "rgb(255,255,255)";\n'
                plote += 'ctx.beginPath();'  
                
                plote += 'ctx.arc(%i+dx,%i+dy,%i,0,Math.PI*2,true);'%(node.x/SCALE, node.y/SCALE, r/SCALE)
                
                plote += 'ctx.stroke();'
                grop = 1
                #if sqrt((x-node.x)**2+(y-node.y)**2) < r:
                numberOfTwos += 1
                logging.info(node)
            else:
                numberOfOthers += 1
                plote += 'ctx.strokeStyle = "rgb(255,0,0)";\n'

            plote += """ctx.beginPath();  
                  ctx.moveTo(%i+dx,%i+dy);  
                  ctx.lineTo(%i+dx,%i+dy);
                  ctx.stroke();
                  ctx.beginPath();  
                  ctx.moveTo(%i+dx,%i+dy);  
                  ctx.lineTo(%i+dx,%i+dy);
                  ctx.stroke();
                  """
            if grop == 0:
                plote = plote%(node.x/SCALE-5, node.y/SCALE-5,
                               node.x/SCALE+5, node.y/SCALE+5,
                               node.x/SCALE-5, node.y/SCALE+5,
                               node.x/SCALE+5, node.y/SCALE-5,)
            else:
                plote = plote%(node.x/SCALE-50, node.y/SCALE-50,
                               node.x/SCALE+50, node.y/SCALE+50,
                               node.x/SCALE-50, node.y/SCALE+50,
                               node.x/SCALE+50, node.y/SCALE-50,)
        template_values = {
                            'drawNodes': plote,
                            'noOfFarms': noOfFarms,
                            'numberOfTwos': numberOfTwos,
                            'numberOfOthers': numberOfOthers,
                        }
        path = os.path.join(os.path.dirname(__file__), 'index.html')
        self.response.out.write(template.render(path, template_values))             
                         
class PutFarms(webapp.RequestHandler):
    def get(self):
        
        header = {"Content-Type": "application/x-www-form-urlencoded"}

        conn = httplib.HTTPConnection("uhrqvist.appspot.com")
        
        nodeRequest = test_pb2.NodeRequest()
        
        for n in range(200):
            mNode1 = nodeRequest.putNodes.add()
            mNode1.resource_key = 2400
            mNode1.x = random.randint(0,2000)
            mNode1.y = random.randint(0,500)
        
        params = nodeRequest.SerializeToString() 
        
        
        conn.request("POST", "/simulatorwebservice/api/proto/node", params , header)
        
        r1 = conn.getresponse()
        logging.info(r1.status)
        logging.info(r1.reason)
        data1 = r1.read()
        conn.close()
        logging.info(data1)
        
class PutCourt(webapp.RequestHandler):
    def get(self):
        
        header = {"Content-Type": "application/x-www-form-urlencoded"}

        conn = httplib.HTTPConnection("uhrqvist.appspot.com")
        
        nodeRequest = test_pb2.NodeRequest()
        
        mNode1 = nodeRequest.putNodes.add()
        mNode1.resource_key = 2459
        mNode1.x = random.randint(0,500)
        mNode1.y = random.randint(0,500)
        
        params = nodeRequest.SerializeToString() 
        
        
        conn.request("POST", "/simulatorwebservice/api/proto/node", params , header)
        
        r1 = conn.getresponse()
        logging.info(r1.status, r1.reason)
        data1 = r1.read()
        conn.close()
        logging.info(data1)        
        
